package com.example.demo.config.shiro;


import com.example.demo.pojo.ShiroUser;
import com.example.demo.pojo.User;
import com.example.demo.service.impl.ShiroUserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自定义Realm
 *
 * @author yzh
 * @date 2023/02/07
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    ShiroUserServiceImpl shiroUserService;

    /**
     * 授权
     *
     * @param principalCollection 主要收集
     * @return {@link AuthorizationInfo}
     *///授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //设置全局权限
//        info.addStringPermission("user:update");
//        info.addStringPermission("user:add");
        //拿到当前用户登陆对象
       /* Subject subject = SecurityUtils.getSubject();
        System.out.println("det:::"+subject.getPrincipal());*/


        //获取登录对象，并转成ShiroUser ,注：这里的是getPrincipal()，如果选择getPrincipals(),得需要后面接上getPrimaryPrincipal()才可以转换成实体类
        ShiroUser currentUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

        /*ShiroUser currentUser = (ShiroUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();*/
        System.out.println("grd:::::" + currentUser);
        String[] split = currentUser.getPerms().split(";");

        for (String s : split) {

            info.addStringPermission(s);
        }
        ;//通过perms值设置当前用户对象权限
        return info;
    }

    /**
     * 做得到身份验证信息
     * 认证
     *
     * @param authenticationToken 身份验证令牌
     * @return {@link AuthenticationInfo}
     * @throws AuthenticationException 身份验证异常
     *///认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证");
        //连接真实数据库
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        ShiroUser shiroUser = shiroUserService.queryUserByName(userToken.getUsername());//获取用户名
        if (shiroUser == null) {//说明查无此人
            return null;
        }
        return new SimpleAuthenticationInfo(shiroUser, shiroUser.getPwd(), "");
    }


}

